package com.lmc.recreation;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lmc.R;
import com.lmc.adapter.RecreationGridListAdapter;
import com.lmc.util.JsonManager;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BannerBean;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.Recreation;
import com.qxzn.app.page.banner.BannerHelper;
import com.qxzn.app.page.robot.RobotHelper;
import com.qxzn.app.page.util.GlideBannerImageLoader;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 娱乐的碎片
 */
public class RecreationFragment extends Fragment implements View.OnClickListener {
    private TextView tv_name;
    private ImageView iv_add;
    private Banner banner;
    private RobotHelper robotHelper;
    private List<BannerBean> bannerList = new ArrayList<>();
    List<String> imageList = new ArrayList<>();

    private ListView listView;
    private RecreationGridListAdapter adapter;
    private List<Recreation.DataBean> list = new ArrayList<>();

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.lmc_fragment_recreation, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        robotHelper = new RobotHelper(getActivity());
        listView.addHeaderView(getHeaderView());
        banner.setImages(imageList).setImageLoader(new GlideBannerImageLoader()).start();
        initBanner();
        tv_name.setOnClickListener(this);
        iv_add.setOnClickListener(this);
        EventBus.getDefault().register(this);
        adapter = new RecreationGridListAdapter(getContext(), list);
        listView.setAdapter(adapter);
        Get();
        updateRobot();

        //调试代码
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String createTime = dateFormat.format(now);

    }

    public View getHeaderView() {
        View view = View.inflate(getContext(), R.layout.recreation_header_layout, null);
        banner = (Banner) view.findViewById(R.id.banner);
        return view;

    }

    private void updateRobot() {
        String name = SharePreferenceUtil.getDeviceName(getContext());
        tv_name.setText(TextUtils.isEmpty(name) ? getText(R.string.no_robot_default_name) : name);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(EventBusBean busBean) {
        if (busBean.getId() == Constant.EventBusId.SWITCH_DEVICE_ID) {
            updateRobot();
            Get();
        }
    }


    private void initView(View view) {
        tv_name = (TextView) view.findViewById(R.id.tv_name);
        iv_add = (ImageView) view.findViewById(R.id.iv_add);
        listView = view.findViewById(R.id.listView);
    }

    private void initBanner() {
        JSONObject params = new JSONObject();
        HttpRequest.getService().getSeriesCarousel(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean<List<BannerBean>>>() {
            @Override
            public void onResponse(Call<BaseBean<List<BannerBean>>> call, Response<BaseBean<List<BannerBean>>> response) {
                BaseBean<List<BannerBean>> body = response.body();
                if (body.getCode() == 200) {
                    Log.e("*****************", "滚动广告：" + body.getData().get(0).type_param);
                    List<BannerBean> bannerBeanList = body.getData();
                    List<String> images = new ArrayList<>();
                    for (BannerBean b : bannerBeanList) {
                        images.add(HttpRequest.BASE_URL + b.bg);
                        Log.e("--------", "图片名称  :" + b.name);
                        Log.e("--------", "图片路径 :" + HttpRequest.BASE_URL + b.bg);
                    }
                    if (images.size() > 0) {
                        updateBanner(images, bannerBeanList);
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseBean<List<BannerBean>>> call, Throwable t) {
                ToastUtil.showTextToast(getContext(), getString(R.string.network_error));
            }
        });
    }

    private void updateBanner(final List<String> images, List<BannerBean> bannerBeanList) {
        banner.setOnBannerListener(null);
        bannerList.clear();
        imageList.clear();
        imageList.addAll(images);
        banner.setImages(imageList);
        if (bannerBeanList != null) {
            bannerList.addAll(bannerBeanList);
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    BannerBean bannerBean = bannerList.get(position);
                    BannerHelper.jumping(getActivity(), bannerBean.type_param, null, bannerBean.name);
                    Log.e("--------", "点击的广告参数  :" + bannerBean.type_param);
                }
            });
        }
        banner.start();
    }

    private void Get() {

        JSONObject params = new JSONObject();
        params.put("robot_id", SharePreferenceUtil.getDeviceId(getContext()));
        HttpRequest.getService().getMediaSection(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
//                    Log.e("-----------", "获取娱乐模块列表：" + string);
                    Recreation recreation = JsonManager.parseJson(string, Recreation.class);
                    list.clear();
                    list.addAll(recreation.getData());
                    adapter.notifyDataSetChanged();

                } catch (Exception e) {
                    Log.e("-----", e.toString());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_name) {
            //机器人的弹窗
            robotHelper.startSwitchRobot(tv_name.getText().toString().trim(), 0);
        } else if (id == R.id.iv_add) {
            //扫一扫添加机器人
            robotHelper.startAddRobot();
        }
//            else if (id == R.id.crosstalk_more) {
//                //相声评书更多
//                startActivity(new Intent(getContext(), RecreationListActivity.class));
//            } else if (id == R.id.opera_more) {
//                //戏曲更多
//                startActivity(new Intent(getContext(), RecreationListActivity.class));
//            } else if (id == R.id.boxue_more) {
//                //卡尔博学更多
//                startActivity(new Intent(getContext(), RecreationListActivity.class));
//            } else if (id == R.id.ertong_more) {
//                //六一儿童网更多
//                startActivity(new Intent(getContext(), RecreationListActivity.class));
//            }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
